package com.foodapp.back.exception;

import com.foodapp.back.common.Result;
import com.foodapp.back.common.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义异常
     */
    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public Result<?> handleApiException(ApiException e) {
        if (e.getErrorCode() != null) {
            return Result.error(e.getErrorCode());
        }
        return Result.error(ResultCode.FAILED, e.getMessage());
    }

    /**
     * 处理参数验证异常
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }
        return Result.validateFailed(message);
    }

    /**
     * 处理其他异常
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result<?> handleException(Exception e) {
        LOGGER.error("系统异常：", e);
        return Result.error(ResultCode.FAILED, e.getMessage());
    }
}
